const express = require('express');
const router = express.Router();
const ArticleCateModel = require('../../model/articleCate.js')
const mongoose = require('../../model/db.js')
router.get('/',async (req,res)=>{
  let result = await ArticleCateModel.aggregate([{
        $lookup:{
            from:"article_cate",
            localField:'_id',
            foreignField:'pid',
            as:'items'
        }
    },{
        $match:{pid:'0'}
    }])
   res.render('admin/articleCate/index',{list:result})
})
router.get('/add',async (req,res)=>{ 
    let topCateList =await ArticleCateModel.find({pid:'0'});
    res.render('admin/articleCate/add',{topCateList})
})
router.post('/doadd',(req,res)=>{
    if(req.body.pid!=0){
        req.body.pid = mongoose.Types.ObjectId(req.body.pid)
    }
    let result = new ArticleCateModel(Object.assign(req.body,{add_time:Date.now()}))
    result.save();
    res.redirect('/admin/articleCate')
   
})
router.get('/edit', async (req,res)=>{
    let id = req.query.id;
    let topCateList =await ArticleCateModel.find({pid:'0'});
    let result =await ArticleCateModel.find({_id:id})
    res.render('admin/articleCate/edit',{topCateList,list:result[0]})
 
})
router.post('/doEdit',async(req,res)=>{
    let id = req.body.id;
    if(req.body.pid != 0){
        req.body.pid = mongoose.Types.ObjectId(req.body.pid);
    }
    await ArticleCateModel.updateOne({_id:id},Object.assign(req.body,{add_time:Date.now()}))
    res.redirect('/admin/articleCate')
})
router.get('/delete',async (req,res)=>{

    let id = req.query.id;
    let result  =await ArticleCateModel.find({pid:mongoose.Types.ObjectId(id)})
    if(result.length>0){
        res.render('admin/status',{
            redirectUrl:'/admin/articleCate',
            title:'删除失败,请先删除此项的子项',
            message:'原页面'
        })
    }else{
        await ArticleCateModel.deleteOne({_id:id});
        res.redirect('/admin/articleCate')
    }
  
})
module.exports = router;